package mi.payment.ui.other;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import mi.payment.BuildConfig;
import mi.payment.R;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.BaseErrorCode;
import mi.payment.constants.Configs;
import mi.payment.constants.Params;
import mi.payment.controller.CheckerController;
import mi.payment.controller.SettlementCtrl;
import mi.payment.db.PayDetailModel;
import mi.payment.settings.SignOperation;
import mi.payment.settings.TransactionSwitchOperation;
import mi.payment.settings.TransactionSwitchSetting;
import mi.payment.transaction.authorize.base.PreAuthorizeMainActivity;
import mi.payment.transaction.balance.BalanceSwingCardActivity;
import mi.payment.transaction.sale.HomeInputMoneyActivity;
import mi.payment.transaction.sale.QRCodeQueryController;
import mi.payment.ui.admin.DownloadManagementActivity;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.SNUtils;
import mi.payment.utils.SettingHomePageUtils;
import mi.payment.utils.transaction.ParamsInitTask;
import mi.payment.utils.transaction.SignOutTask;
import sunmi.sunmiui.dialog.DialogCreater;
import sunmi.sunmiui.dialog.HintDialog;
import sunmi.sunmiui.dialog.HintOneBtnDialog;
import sunmi.sunmiui.dialog.ListDialog;
import sunmi.sunmiui.title.Title;
import sunmi.sunmiui.utils.LogUtil;

/**
 * 管理界面
 *
 * @author by longx on 2017/3/25.
 */

public class OrdinaryUserManageActivity extends ParentActivity {

    private HintDialog hintDialog;
    private HintOneBtnDialog oneBtnDialog;
    private ListDialog mListDialog;
    private QRCodeQueryController qrCodeLastOrderQueryExt;
    private SettingHomePageUtils settingHomePageUtils = SettingHomePageUtils.getInstance();
    String oldHome;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ordinary_user_manage);
        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        TextView txt_version = (TextView) this.findViewById(R.id.txt_version);
        TextView txt_sn = (TextView) this.findViewById(R.id.txt_sn);
        String version = getString(R.string.now) + getString(R.string.version, BuildConfig.VERSION_NAME);
        String sn = "SN:" + SNUtils.getBindSN();
        txt_sn.setText(sn);
        txt_version.setText(version);
        RelativeLayout itemBalance = (RelativeLayout) findViewById(R.id.item_balance);
        RelativeLayout itemSettlement = (RelativeLayout) findViewById(R.id.item_settlement);
        RelativeLayout itemSignOut = (RelativeLayout) findViewById(R.id.item_sign_out);
        RelativeLayout itemOperatorPwd = (RelativeLayout) findViewById(R.id.item_operator_update_pwd);
        RelativeLayout itemSettingHome = (RelativeLayout) findViewById(R.id.item_setting_home);
        RelativeLayout itemQrSwitchCtrl = (RelativeLayout) findViewById(R.id.item_qr_switch_control);
        RelativeLayout itemLastOrder = (RelativeLayout) findViewById(R.id.item_last_order);
        RelativeLayout itemOrderSetting = (RelativeLayout) findViewById(R.id.item_order_setting);
        RelativeLayout itemTerms = (RelativeLayout) findViewById(R.id.item_terms);

        // +sunhengzhi, 2017-09-20, 管理中新增参数下载、参数打印菜单
        RelativeLayout itemParamsDownload = (RelativeLayout) findViewById(R.id.item_params_download);
        RelativeLayout itemParamsPrint = (RelativeLayout) findViewById(R.id.item_params_print);
        // -sunhengzhi, 2017-09-20, 管理中新增参数下载、参数打印菜单

        TextView itemText = (TextView) itemBalance.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.balance_query_title));

        itemText = (TextView) itemSettlement.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.settlement));

        itemText = (TextView) itemSignOut.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.sign_out_now));

        itemText = (TextView) itemOperatorPwd.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.operator_update_pwd));

        itemText = (TextView) itemSettingHome.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.setting_common_home));
        showNowHome(itemSettingHome);

        itemText = (TextView) itemQrSwitchCtrl.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.qr_code_transaction_switch_settings));

        itemText = (TextView) itemLastOrder.findViewById(R.id.item_left_text);
        itemText.setText(getString(R.string.ordinary_user_manager_last_order));

        // +sunhengzhi, 2017-09-20, 管理中新增参数下载、参数打印菜单
        itemText = (TextView) itemParamsDownload.findViewById(R.id.item_left_text);
        itemText.setText(R.string.download_function);

        itemText = (TextView) itemParamsPrint.findViewById(R.id.item_left_text);
        itemText.setText(R.string.parameters_print);
        // -sunhengzhi, 2017-09-20, 管理中新增参数下载、参数打印菜单

        itemText = (TextView) itemOrderSetting.findViewById(R.id.item_left_text);
        itemText.setText(R.string.order_setting_title);


        itemBalance.setOnClickListener(this);
        itemSettlement.setOnClickListener(this);
        itemSignOut.setOnClickListener(this);
        itemOperatorPwd.setOnClickListener(this);
        itemSettingHome.setOnClickListener(this);
        itemQrSwitchCtrl.setOnClickListener(this);
        itemLastOrder.setOnClickListener(this);
        itemParamsDownload.setOnClickListener(this);
        itemParamsPrint.setOnClickListener(this);
        itemOrderSetting.setOnClickListener(this);
        itemTerms.setOnClickListener(this);

        Title title;
        title = (Title) findViewById(R.id.title_manager);
        title.setButtonVisibility(false, true, true, true);
        title.setHeadBgColor(getResources().getColor(R.color.colorBar));
        title.setTitleText(getResources().getString(R.string.management));
        title.setImageViewBackDrawable(R.drawable.ic_back);
        title.setMenuClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }

        }, null, null, null);

        if (Configs.getInstance().QUERY_LAST_TRANSACTION()) {
            qrCodeLastOrderQueryExt = new QRCodeQueryController(this);
        } else {
            itemLastOrder.setVisibility(View.GONE);
        }

        // 扫码类控制开关
        if (Configs.getInstance().MANAGER_QR_CODE_SWITCH()) {
            itemQrSwitchCtrl.setVisibility(View.VISIBLE);
        } else {
            itemQrSwitchCtrl.setVisibility(View.GONE);
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_balance:
                // 余额查询
                TransactionSwitchSetting tss = TransactionSwitchOperation.getInstance().getTransactionSwitchSetting();
                if (tss.isQueryBalance()) {
                    openActivity(BalanceSwingCardActivity.class);
                } else {
                    showOneBtnDialog(getString(R.string.ordinary_nosupport));
                }
                break;
            case R.id.item_settlement:
                // 结算
                showSettlementDialog();
                break;
            case R.id.item_sign_out:
                // 签退
                if (!new CheckerController(this).isComplete()) {
                    showToast(getString(R.string.parameter_no_complete));
                    return;
                }
                if (!ParamsInitTask.isChecked) {
                    showToast(getString(R.string.no_checkin_dialog_msg_4_checkout));
                    return;
                }
                boolean haveNum = haveSerialNum();
                if (haveNum) {
                    showPromptDialog();
                } else {
                    showLogoutDialog();
                }
                break;
            case R.id.item_operator_update_pwd:
                // 操作员改密
                openActivity(UpdatePwdInputAdminPwd.class);
                break;
            case R.id.item_setting_home:
                // 设置常用首页
                String[] item = {getResources().getString(R.string.consume_page), getResources().getString(R.string.pre_page)};
                mListDialog = DialogCreater.createListDialog(this, getResources().getString(R.string.set_to), getResources().getString(R.string.cancel), item);
                mListDialog.setItemClickListener(mItemClickListener);
                mListDialog.show();
                break;
            case R.id.item_qr_switch_control:
                // 扫码类交易开关控制
                openActivity(QRCodeTransactionSwitchAdminPwd.class);
                break;
            case R.id.item_last_order:
                qrCodeLastOrderQueryExt.queryLastQRCodeTrade();
                break;
            // +sunhengzhi, 2017-09-20, 管理中新增参数下载、参数打印菜单
            case R.id.item_params_download:
                switch (BuildConfig.FLAVOR) {
                    case "lePos": // 乐刷不需要输密
                        openActivity(DownloadManagementActivity.class);
                        break;
                    default:
                        openActivity(ParamsDownloadAdminPwd.class);
                        break;
                }
                break;
            case R.id.item_params_print:
                startActivity(new Intent(this, ParamsPrintAdminPwd.class));
                break;
            // -sunhengzhi, 2017-09-20, 管理中新增参数下载、参数打印菜单

            case R.id.item_order_setting:
                startActivity(new Intent(this, OrderSettingActivity.class));
                break;
            case R.id.item_terms:
                break;
            default:
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (hintDialog != null) {
            hintDialog.dismiss();
            hintDialog = null;
        }
        if (oneBtnDialog != null) {
            oneBtnDialog.dismiss();
            oneBtnDialog = null;
        }
        if (mListDialog != null) {
            mListDialog.dismiss();
            mListDialog = null;
        }
    }

    private void showLogoutDialog() {
        hintDialog = DialogCreater.createHintDialog(this, R.drawable.img_warning, getString(R.string.cancel),
                getString(R.string.ok), getString(R.string.are_you_sure_sign_out),
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (hintDialog != null) {
                            hintDialog.dismiss();
                        }
                    }

                }, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (hintDialog != null) {
                            hintDialog.dismiss();
                        }
                        logout();
                    }

                }, false);
        hintDialog.setCancelable(true);
        hintDialog.setCanceledOnTouchOutside(true);
        hintDialog.show();
    }

    /**
     * 签退
     */
    private void logout() {
        SignOutTask task = new SignOutTask(this) {

            @Override
            protected void onPostExecuteImpl(TradeData trade) {
                String code = trade.getPayDetail().getTradeAnswerCode();
                if (code.equals("00")) {
                    showToast(getResources().getString(R.string.sign_out_success));
                    LoginActivity.startAction(OrdinaryUserManageActivity.this, true);
                    // 清除当前的签到时间
                    SignOperation.getInstance().saveLastSignTime(0);
                    // 重置是否已经签到的标志位
                    ParamsInitTask.isChecked = false;
                    finish();
                } else {
                    showToast(getString(R.string.sign_out_fail, BaseErrorCode.getCode(code)));
                }
            }

        };
        task.setLoadDialog(getLoadingDialog(getString(R.string.sign_out)));
        task.execute(Params.newTradeData());
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 发起结算
     */
    protected void showSettlementDialog() {
        hintDialog = DialogCreater.createHintDialog(this, R.drawable.img_warning,
                getString(R.string.cancel), getString(R.string.confirm), getString(R.string.settlement_dialog_msg),
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (hintDialog != null) {
                            hintDialog.dismiss();
                        }
                    }

                },
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (hintDialog != null) {
                            hintDialog.dismiss();
                        }
                        settlement();
                    }

                }, false);
        hintDialog.setCancelable(true);
        hintDialog.setCanceledOnTouchOutside(true);
        hintDialog.show();
    }

    private void showPromptDialog() {
        hintDialog = DialogCreater.createHintDialog(OrdinaryUserManageActivity.this, R.drawable.img_warning, getString(R.string.ok), null, getString(R.string.have_serial_num_prompt), new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (hintDialog != null) {
                    hintDialog.dismiss();
                }
            }

        }, null, false);
        hintDialog.setCancelable(true);
        hintDialog.setCanceledOnTouchOutside(true);
        hintDialog.show();
    }

    private void settlement() {
        SettlementCtrl ctrl = new SettlementCtrl(this);
        ctrl.settlement();
    }

    protected void showOneBtnDialog(String msg) {
        oneBtnDialog = DialogCreater.createHintOneBtnDialog(this,
                getString(R.string.ordinary_hint), msg, getString(R.string.confirm),
                new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        if (oneBtnDialog != null) {
                            oneBtnDialog.dismiss();
                        }
                    }

                });
        oneBtnDialog.setCancelable(true);
        oneBtnDialog.setCanceledOnTouchOutside(true);
        oneBtnDialog.show();
    }

    private boolean haveSerialNum() {
        int count = PayDetailModel.getInstance().getTransactionList().size();
        return count > 0;
    }

    private ListDialog.ItemClickListener mItemClickListener = new ListDialog.ItemClickListener() {

        @Override
        public void OnItemClick(int position) {
            RelativeLayout itemSettingHome = (RelativeLayout) findViewById(R.id.item_setting_home);
            TextView itemText = (TextView) itemSettingHome.findViewById(R.id.item_right_text);
            mListDialog.dismiss();

            switch (position) {
                case 0:
                    settingHomePageUtils.setOftenHomePage("HomeInputMoneyActivity");
                    itemText.setText(R.string.consume_page);
                    break;
                case 1:
                    settingHomePageUtils.setOftenHomePage("PreAuthorizeMainActivity");
                    itemText.setText(R.string.pre_page);
                    break;
            }
        }
    };

    /**
     * 显示当前首页
     *
     * @return
     */
    public void showNowHome(RelativeLayout itemSettingHome) {
        SettingHomePageUtils.SettingHome settingHome = settingHomePageUtils.getSettingHome();
        TextView itemText = (TextView) itemSettingHome.findViewById(R.id.item_right_text);
        if (settingHome != null) {
            oldHome = settingHome.nowHome;
            if (settingHome.nowHome.equals("PreAuthorizeMainActivity")) {
                itemText.setText(R.string.pre_page);
            } else {
                itemText.setText(R.string.consume_page);
            }
        } else {
            itemSettingHome.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        SettingHomePageUtils.SettingHome settingHome = settingHomePageUtils.getSettingHome();
        if (settingHome == null) {
            LogUtil.e("lzc", "不需要进行设置首页");
        } else if (settingHome.nowHome.equals(oldHome)) {
            LogUtil.e("lzc", "未修改常用首页");
        } else {
            sendCloseHomeActivityBroadcast();
            if (settingHome.nowHome.equals("PreAuthorizeMainActivity")) {
                openActivity(PreAuthorizeMainActivity.class);
            } else {
                openActivity(HomeInputMoneyActivity.class);
            }
        }
        super.onBackPressed();
    }
}
